import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Outlet, useNavigation, useLocation, useNavigate } from 'react-router-dom';
import {
    AppstoreOutlined,
    ContainerOutlined,
    DesktopOutlined,
    MailOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    PieChartOutlined,
    LogoutOutlined,
    SettingOutlined,
} from '@ant-design/icons';
import { Button, Menu, Layout, Drawer, Input, Avatar, Popover, Divider, FloatButton } from 'antd';
import { useAuth } from '@/components/auth';
import * as api from '@/mock/menu';
import { useNav } from '@/components/nav';
import Breadcrumb from '@/components/breadcrumb';
import { useRootConfig } from '@/components/root-config';
import SettingDrawer from './SettingDrawer';
import SelectLang from './SelectLang';
import { useIntl } from '@/components/locale';
import './index.less';

const { Header, Sider } = Layout;
const iconMap: any = {
    AppstoreOutlined: <AppstoreOutlined />,
    ContainerOutlined: <ContainerOutlined />,
    DesktopOutlined: <DesktopOutlined />,
    MailOutlined: <MailOutlined />,
    PieChartOutlined: <PieChartOutlined />,
};

// 递归获取点击的菜单项
function getMenuItemByKeyPath(data: { [key: string]: any }[] | null, keyPath: string, arr: string[] = []): any {
    if (!data) return null;
    let result = null;
    for (let i = 0; i < data.length; i += 1) {
        const { key, type, children } = data[i];

        if (type === 'group') {
            result = getMenuItemByKeyPath(children, keyPath, arr);
        } else {
            const curKeyPath = [key, ...arr];
            if (keyPath.length === curKeyPath.length && keyPath.toString() === curKeyPath.toString()) {
                result = data[i];
            } else if (children) {
                result = getMenuItemByKeyPath(children, keyPath, curKeyPath);
            }
        }

        if (result) {
            break;
        }
    }
    return result;
}

/**
 * 门户页
 * @returns
 */
function LayoutPage() {
    const navigation = useNavigation();
    const navigate = useNavigate();
    const { pathname } = useLocation();
    const { nav } = useNav();
    const { user, signout } = useAuth();

    const [collapsed, setCollapsed] = useState(true);

    const [open, setOpen] = useState(false);
    const [menuData, setMenuData] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    const [openKeys, setPpenKeys] = useState([]);
    const activeKey: string = pathname.replace(/\/portal\/?/i, '') || 'home';

    const {
        layout: { menuMode },
        theme,
    } = useRootConfig();

    const intl = useIntl();

    /**
     * 请求接口获取菜单
     */
    useEffect(() => {
        api.getMenu(1).then((res: any) => {
            if (res?.code === 0) {
                setMenuData(res.data);
            }
        });
    }, []);

    useEffect(() => {
        setSelectedKeys([activeKey]);
    }, [activeKey]);

    const menuItems = useMemo(() => {
        /**
         * 格式化菜单数据
         * @param {*} data
         * @returns
         */
        function formatMenu(data: any) {
            if (!data) return null;
            return data.map(({ children, icon, langID, label, ...item }: any) => ({
                ...item,
                id: langID,
                label: langID
                    ? intl.formatMessage({
                          id: langID,
                          defaultMessage: label,
                      })
                    : label,
                icon: iconMap[icon],
                children: formatMenu(children),
            }));
        }
        return formatMenu(menuData);
    }, [intl, menuData]);

    // 切换展开\收起
    const toggleCollapsed = useCallback(
        function toggleCollapsed() {
            setCollapsed(!collapsed);
        },
        [collapsed],
    );

    // 点击菜单项
    const onMenuClick = useCallback(
        function onMenuClick(info: any) {
            const { key, keyPath } = info;
            const item = getMenuItemByKeyPath(menuItems, keyPath);
            nav({
                key,
                label: item?.label,
                langID: item?.langID,
                options: {
                    replace: true,
                },
            });
        },
        [menuItems, nav],
    );

    // 关闭抽屉
    const onDrawerClose = useCallback(function onDrawerClose() {
        setOpen(false);
    }, []);

    /**
     * 搜索
     */
    const onSearch = useCallback(function onSearch() {}, []);

    return (
        <Layout className='portal-container h-full w-full flex flex-col mx-auto'>
            <div className=' fixed top-0 left-0'>{navigation.state !== 'idle' && <p>导航正在进行...</p>}</div>
            <Header className='portal-header flex items-center justify-between text-center'>
                <div className='flex items-center'>
                    <Button type='primary' onClick={toggleCollapsed}>
                        {collapsed ? <MenuUnfoldOutlined title='展开' /> : <MenuFoldOutlined title='收起' />}
                    </Button>
                    <div className='ml-4'>
                        {intl.formatMessage({
                            id: 'pages.welcome.link',
                            defaultMessage: '欢迎使用',
                        })}
                    </div>
                    <div className='ml-4'>
                        <Button
                            type='link'
                            target='_blank'
                            href='#/root/shop'
                            // href='#/root/shop'
                        >
                            商城
                        </Button>
                    </div>
                    <div className='ml-4'>
                        <Button type='link' target='_blank' href='root/live'>
                            直播
                        </Button>
                    </div>
                    <div className='ml-4'>
                        <Button type='link' target='_blank' href='root/game'>
                            游戏
                        </Button>
                    </div>
                </div>
                <div className=' flex items-center'>
                    <Input.Search
                        size='middle'
                        placeholder='input search text'
                        allowClear
                        onSearch={onSearch}
                        className=' w-60 mr-4'
                    />
                    <SelectLang />
                    <Popover
                        content={
                            <div className=' w-80 h-44 flex flex-col -mt-3 -mb-3'>
                                <div className='flex flex-1 items-center'>
                                    <div className='flex items-center flex-1 relative'>
                                        <Avatar
                                            src='https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
                                            size={90}
                                        />
                                        <div className='ml-4'>{user?.name}</div>
                                    </div>
                                    <Button
                                        onClick={async () => {
                                            signout();
                                        }}
                                        className=' absolute top-2 right-2'
                                        type='link'
                                        icon={<LogoutOutlined />}
                                    >
                                        退出登录
                                    </Button>
                                </div>
                                <Divider className=' m-0' />
                                <div className=' flex items-center justify-center h-16'>
                                    <div className='flex-1 text-center'>个人中心</div>
                                    <div className='flex-1 text-center'>个人设置</div>
                                </div>
                            </div>
                        }
                    >
                        <Avatar
                            src='https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
                            size={50}
                        />
                    </Popover>
                </div>
            </Header>
            <Layout className=' relative'>
                <Breadcrumb menus={menuItems} />
                <Layout>
                    <FloatButton
                        type='primary'
                        icon={<SettingOutlined />}
                        onClick={() => {
                            setOpen(true);
                        }}
                    />
                    <Drawer
                        className='portal-drawer'
                        title='设置'
                        placement='right'
                        onClose={onDrawerClose}
                        open={open}
                        rootStyle={{
                            top: 89,
                        }}
                    >
                        <SettingDrawer />
                    </Drawer>
                    <Layout hasSider>
                        <Sider
                            className='portal-sider overflow-auto'
                            theme={theme}
                            collapsible
                            collapsed={collapsed}
                            onCollapse={(value) => setCollapsed(value)}
                            collapsedWidth={40}
                        >
                            <Menu
                                selectedKeys={selectedKeys}
                                openKeys={openKeys}
                                mode={menuMode}
                                theme={theme}
                                items={menuItems}
                                onClick={onMenuClick}
                                onSelect={(info: any) => {
                                    setSelectedKeys(info.selectedKeys);
                                }}
                                onOpenChange={(openKeys: any) => {
                                    setPpenKeys(openKeys);
                                }}
                                className='portal-menu'
                            />
                        </Sider>
                        <Layout className='portal-content overflow-hidden p-2'>
                            <Layout className='portal-page-container h-full rounded-md overflow-hidden'>
                                <Outlet />
                            </Layout>
                        </Layout>
                    </Layout>
                </Layout>
            </Layout>
        </Layout>
    );
}

export default LayoutPage;
